<template>
  <div>
    <template v-if="isShowPDF">
      <Pdf v-for="index in numPages" :key="index" :src="pdfUrl" :page="index"/>
      <el-button @click="downloadPdf" style=" position: fixed; bottom: 20px; right: 20px;">下载保存</el-button>
    </template>
    <h1 v-else style="text-align: center" v-if="!isShowPDF">
      {{ msg }} </h1>
  </div>
</template>
<script>
  import Pdf from "vue-pdf";
  import {jieKouPDF} from "@/api/jiekou/jiekou";

  export default {
    components: {Pdf},
    data() {
      return {
        numPages: null,
        isShowPDF: true,
        pdfUrl: '',
        msg: null
      };
    },
    props: {
      PDFfileInfo: {
        type: Object,
        default: () => ({jfCode: '', name: '', source: ''})
      }
    },

    created() {
      var jfCode = this.PDFfileInfo.jfCode
      if (jfCode == 'JF011' || jfCode == 'JF015' || jfCode == 'JF016' || jfCode == 'JF017'|| jfCode == 'JF020'  ) {
        // 判断展示
        this.isShowPDF = false
        this.msg = '前往接口说明下载即可查看'
        return
      } else if(jfCode == 'JF012'){
        this.isShowPDF = false
        this.msg = '对应接口即可查看'
        return
      }else if(jfCode == 'JF019'){
        this.isShowPDF = false
        this.msg = '暂无'
        return
      }
      jieKouPDF(this.PDFfileInfo.name).then(response => {
          this.pdfUrl = this.getObjectURL(response)
          this.loadPdf()
        }
      );
    },

    methods: {
      getObjectURL(data) {
        let url = null;
        let file = new Blob([data], {type: "application/pdf"});
        if (window.createObjectURL != undefined) {
          // 通用
          url = window.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
          // 兼容谷歌
          try {
            url = window.webkitURL.createObjectURL(file);
          } catch (error) {
          }
        } else if (window.URL != undefined) {
          // 兼容其他
          try {
            url = window.URL.createObjectURL(file);
          } catch (error) {
          }
        }
        // 将转化后url赋值
        return url
      },

      loadPdf() {
        this.pdfUrl = Pdf.createLoadingTask(this.pdfUrl)
        this.pdfUrl.promise.then(Pdf => {
          this.$nextTick(() => {
            this.numPages = Pdf.numPages // pdf总页数
          })
        })
      },

      downloadPdf() {
        jieKouPDF(this.PDFfileInfo.name).then(response => {
            let blob = new Blob([response], {
              type: `application/pdf` //word文档为msword,pdf文档为pdf
            });
            let objectUrl = URL.createObjectURL(blob);
            let link = document.createElement("a");
            let fname = this.PDFfileInfo.name; //下载文件的名字
            link.href = objectUrl;
            link.setAttribute("download", fname);
            document.body.appendChild(link);
            link.click();
          }
        );

      }
    }
  };

</script>

<style>

</style>
